package leetcode.code443.StringCompression;

import leetcode.helper.HelpDebug;

public class Solution44301 extends StringCompression {

	@Override
	public int compress(char[] chars) {
		int len = chars.length;
		if (len == 1) {
			return 1;
		}
		int l = 0;// 左侧最后一个被占用的下标
		int r = 0;
		int size = 0;
		while (r < len) {
			r++;
			size++;
			if (r == len || chars[l] != chars[r]) {
				if (size > 1) {
					if (size < 10) {
						chars[++l] = (char) (size + 48);
					} else {
						int temp = l + 1;
						while (size > 0) {
							chars[++l] = (char) (size % 10 + 48);
							size = size / 10;
						}
						this.reverse(chars, temp, l);
					}
				}
				if (r < len) {
					chars[++l] = chars[r];
					size = 0;
				}
			}
		}
		HelpDebug.printObject(chars);
		return l + 1;
	}

	public void reverse(char[] chars, int x, int y) {
		for (int i = x, j = y; i < j; i++, j--) {
			char temp = chars[x];
			chars[x] = chars[y];
			chars[y] = temp;
		}
	}

	public static void main(String[] args) {
		Solution44301 i = new Solution44301();
		i.debug1();
		i.debug2();
		i.debug3();
		i.debug4();
		i.debug5();

//		int temp = 1234;
//		while (temp > 0) {
//			char c = (char) (temp % 10 + 48);
//			System.out.println(c);
//			temp = temp / 10;
//		}
	}

}
